package de.tum.in.eist.poll.client.widgets.content;

import java.util.ArrayList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

import de.tum.in.eist.poll.client.PollService;
import de.tum.in.eist.poll.client.PollServiceAsync;
import de.tum.in.eist.poll.client.widgets.other.LectureLinkClickHandler;
import de.tum.in.eist.poll.shared.Lecture;
import de.tum.in.eist.poll.shared.User;

/**
 * Factory product that displays the lecture overview UI
 * @author aperture
 *
 */
public class LectureOverviewUI extends Composite implements Content {
	private static User user = null;
	private final PollServiceAsync pollService = GWT.create(PollService.class);

	private Widget initialization() {
		final VerticalPanel container = new VerticalPanel();
		final VerticalPanel top = new VerticalPanel();
		final VerticalPanel bottom = new VerticalPanel();

		pollService.loginFromSession(new AsyncCallback<User>() {
			public void onFailure(Throwable error) {

			}

			public void onSuccess(User result) {
				user = result;
			}
		});

		container.add(top);
		container.add(bottom);

		pollService.requestLectures(new AsyncCallback<ArrayList<Lecture>>() {
			@Override
			public void onSuccess(ArrayList<Lecture> result) {
				final FlexTable courseTable = new FlexTable();
				
				courseTable.setWidget(0, 0, new HTML("<h2>Your attended lectures (" + user.getName() + "):</h2>"));
				
				if (result.size() != 0) {
					int row = 1;
					for (Lecture l : result) {				
						final Anchor link = new Anchor(l.getParentCourseTitle() + " ("
								+ l.getParentCourseCode() + ") -- " + l.getNumber()
								+ " - " + l.getTitle() + " (" + l.getDate() + ")");
						
						link.addClickHandler(new LectureLinkClickHandler(l, bottom)); 
						courseTable.setWidget(row++, 0, link);				
					}
				}
				top.add(courseTable);
			}

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}
		});

		return container;
	}

	@Override
	public Widget draw() {
		initWidget(initialization());
		return this;
	}

}
